package com.light.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.gulimall.product.dao.AttrGroupDao;
import com.light.gulimall.product.dao.SkuImagesDao;
import com.light.gulimall.product.dao.SkuInfoDao;
import com.light.gulimall.product.dao.SpuInfoDescDao;
import com.light.gulimall.product.entity.SkuImagesEntity;
import com.light.gulimall.product.entity.SkuInfoEntity;
import com.light.gulimall.product.entity.SpuInfoDescEntity;
import com.light.gulimall.product.feign.SeckillRemoteServiceClient;
import com.light.gulimall.product.service.SkuInfoService;
import com.light.gulimall.product.to.SecKillSkuRedisTO;
import com.light.gulimall.product.vo.SkuDetailsVO;
import com.light.gulimall.product.vo.SkuItemSaleAttrVO;
import com.light.gulimall.product.vo.SpuItemBaseAttrVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    /**
     * sku图片信息
     */
    @Autowired
    private SkuImagesDao skuImagesDao;

    /**
     * spu 信息
     */
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    /**
     * pms_attr_group
     */
    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private SeckillRemoteServiceClient seckillRemoteServiceClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * sku检索
     *
     * @param params 查询条件
     * @return 分页结果
     */
    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        try {
            QueryWrapper<SkuInfoEntity> skuInfoEntityQueryWrapper = new QueryWrapper<>();

            String key = (String) params.get("key");
            if (!StringUtils.isBlank(key)) {
                skuInfoEntityQueryWrapper.and((w) -> {
                    w.eq("sku_id", key).or().like("sku_name", key);
                });
            }

            String brandId = (String) params.get("brandId");
            if (!brandId.equals("0")) {
                skuInfoEntityQueryWrapper.eq("brand_id", brandId);
            }

            String catelogId = (String) params.get("catelogId");
            if (!catelogId.equals("0")) {
                skuInfoEntityQueryWrapper.eq("catalog_id", catelogId);
            }

            //价格区间
            String minStr = (String) params.get("min");
            String maxStr = (String) params.get("max");

            BigDecimal min = new BigDecimal(minStr);
            BigDecimal max = new BigDecimal(maxStr);
            if (!minStr.equals("0") && !maxStr.equals("0")) {
                skuInfoEntityQueryWrapper.ge("price", min).le("price", max);
            }

            IPage<SkuInfoEntity> page = this.page(
                    new Query<SkuInfoEntity>().getPage(params),
                    skuInfoEntityQueryWrapper
            );

            return new PageUtils(page);
        } catch (Exception e) {
            log.error("发生异常:", e);
            return null;
        }
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     * 根据SkuId查询详情信息
     * @param skuId skuId
     * @return 查询结果
     */
    @Override
    public SkuDetailsVO skuItem(Long skuId) {
        SkuDetailsVO vo = new SkuDetailsVO();

        //异步执行1、sku基本信息
        CompletableFuture<SkuInfoEntity> skuInfoEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = getById(skuId);
            vo.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        //获取 1、sku基本信息结果，执行3、销售属性组合
        CompletableFuture<Void> SkuItemSaleAttrFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((skuInfoEntity) -> {
            Long spuId = skuInfoEntity.getSpuId();
            //3、销售属性组合 依赖1
            List<SkuItemSaleAttrVO> skuItemSaleAttr = skuInfoDao.getSkuItemSaleAttr(spuId);
            vo.setSkuItemSaleAttr(skuItemSaleAttr);
        }, threadPoolExecutor);

        //获取 1、sku基本信息结果，执行4、SPU 详情介绍
        CompletableFuture<Void> spuInfoDescFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((skuInfoEntity) -> {
            //4、SPU 详情介绍 依赖1
            SpuInfoDescEntity spuInfoDescEntity = this.spuInfoDescDao.selectOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", skuInfoEntity.getSpuId()));
            vo.setSpuInfo(spuInfoDescEntity);
        }, threadPoolExecutor);


        //获取 1、sku基本信息结果，执行5、spu规格参数信息
        CompletableFuture<Void> spuItemBaseAttrFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((skuInfoEntity) -> {
            //5、spu规格参数信息 依赖1
            //根据catalogId去查询pms_attr_group表
            List<SpuItemBaseAttrVO> spuItemBaseAttr = attrGroupDao.getSpuItemBaseAttr(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());
            vo.setSpuItemBaseAttr(spuItemBaseAttr);
        }, threadPoolExecutor);


        //获取图片信息另外开一个线程，不需要等待其他任务的结果
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2、sku图片信息
            List<SkuImagesEntity> skuImagesEntityList = this.skuImagesDao.selectList(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            vo.setSkuImages(skuImagesEntityList);
        }, threadPoolExecutor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            //远程调用seckill服务，判断当前商品是否参与秒杀
            SecKillSkuRedisTO secKillSkuRedisTO = seckillRemoteServiceClient.getCurrentSeckillSkuById(skuId);
            vo.setSecKillSkuRedisTO(secKillSkuRedisTO);
        }, threadPoolExecutor);


        //等到所有任务执行完成
        CompletableFuture.allOf(SkuItemSaleAttrFuture, spuItemBaseAttrFuture, spuInfoDescFuture, imageFuture,seckillFuture).join();

        return vo;
    }


}